package tomasulo.component;

import tomasulo.Driver;
import tomasulo.unit.Instr;

public class Loader extends Component {

	private int addr = 0;
	private Float cache = null;
	private static final int TIME_DELAY = 2;

	public Loader(String name) {
		super(name);
	}

	@Override
	public void afterTick(int tick) {
		if (busy) {
			if (time > 0) {
				--time;
				if (time == 0) {
					cache = Driver.getMemory().getAt(addr);
					instr.setTimeComp(tick);
				}
			} else if (time == 0){
				instr.setTimeWrite(tick);
				Driver.putCDB(name, new Float(cache));
				reset();
			}
		}
	}

	@Override
	public void checkCDB(int tick) {
	}

	@Override
	public boolean issue(Instr instr) {
		if (busy)
			return false;
		if (!instr.op.equals(Instr.OP.LD))
			return false;
		this.instr = instr;
		addr = instr.op1;
		Driver.getFU().get(instr.op0).setStation(name);
		busy = true;
		cache = null;
		time = TIME_DELAY; 	// Don't need to wait
		return true;
	}

	public int getAddr() {
		return addr;
	}
	
	public Float getCache() {
		return cache;
	}

	@Override
	public void reset() {
		// TODO Auto-generated method stub
		busy = false;
		addr = 0;
		cache = null;
		time = 0;
	}

}
